package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	. "mwwow_service_go/model"
	"strconv"
)

// 增加文章
func AddArticle(c *gin.Context) {
	var article ArticleRequest
	err := json.NewDecoder(c.Request.Body).Decode(&article)
	if err != nil {
		log.Fatalln(err)
	}
	id, err := article.SaveArticle()
	if err != nil {
		log.Fatalln(err)
		return
	}
	c.JSON(200, gin.H{
		"code":     0,
		"insertId": id,
	})
}

// 删除文章
func DelArticle(c *gin.Context) {
	var article ArticleRequest
	id := c.Param("id")
	isSuccess, err := article.DeleteArticle(id)
	if err != nil || isSuccess != true {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
	})
}

// 修改文章
func UpdateArticle(c *gin.Context) {
	var article ArticleRequest
	id := c.Param("id")
	err := json.NewDecoder(c.Request.Body).Decode(&article)
	if err != nil {
		log.Fatal(err)
	}
	isSuccess, err := article.UpdateArticle(id)
	if err != nil || isSuccess != true {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
	})
}

// 获取文章列表
func GetArticle(c *gin.Context) {
	var article Article
	var data []Article
	var total int
	var err error
	id := c.Query("typeId")
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	if id != "" {
		data, total, err = article.GetArticleByType(id, pageNum, pageSize)
	} else {
		data, total, err = article.GetArticle(pageNum, pageSize)
	}
	if err != nil {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  0,
		"data":  data,
		"total": total,
	})
}

func GetNoticeInfo(c *gin.Context) {
	var article Article
	data := article.GetNotice()
	c.JSON(200, gin.H{
		"code": 0,
		"data": data,
	})
}

// 根据id获取指定文章
func GetArticleById(c *gin.Context) {
	var article Article
	id := c.Param("id")
	data, err := article.GetArticleById(id)
	if err != nil {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": data,
	})
}

// 上传图片
func UploadFile(c *gin.Context) {
	var article Article
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		log.Fatalln(err)
	}
	pathName, err := article.Upload(file, header)
	if err != nil {
		log.Fatalln(err)
		c.JSON(500, gin.H{
			"code":  1,
			"error": err,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"path": pathName,
	})
}
